<?php

namespace app\modules\cn\controllers;

use app\modules\app\models\QuestionCollect;
use app\modules\cn\models\ExerciseListDetail;
use app\modules\cn\models\ExerciseResult;
use app\modules\cn\models\MockAnswer;
use app\modules\cn\models\MockCate;
use app\modules\cn\models\MockInfo;
use app\modules\cn\models\MockPublic;
use app\modules\cn\models\MockQuestionSign;
use app\modules\cn\models\QuestionRemarks;
use app\modules\cn\models\User;
use yii;
use app\libs\IeltsController;
use app\modules\cn\models\ExerciseList;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class MockController extends IeltsController
{
    public $enableCsrfValidation = false;
    public $layout = 'share';

    public function actionSave()
    {
        $listen = ExerciseList::MockData('x2_exercise_category.pid=413 and x2_exercise_category.isShow=1', 4);
        $read = ExerciseList::MockData('x2_exercise_category.pid=462 and x2_exercise_category.isShow=1', 3);
        $write = ExerciseList::MockData('x2_exercise_category.pid=512 and x2_exercise_category.cate_id!=521 and x2_exercise_category.isShow=1', 2);
        $speak = ExerciseList::MockData('x2_exercise_category.pid=537 and x2_exercise_category.cate_id!=549 and x2_exercise_category.isShow=1', 3);
        for ($i = 0; $i < 24; $i++) {
            $re = Yii::$app->db->createCommand()->insert("{{%mock_cate}}", ['listen' => implode(',', array_column($listen[$i], 'content_id')), 'read' => implode(',', array_column($read[$i], 'content_id')), 'speak' => implode(',', array_column($speak[$i], 'content_id')), 'write' => implode(',', array_column($write[$i], 'content_id'))])->execute();
        }
    }

    /**
     * @Title  模考列表
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionList()
    {
        $type = Yii::$app->request->get('type', 1);//听力1 阅读2 全套5
        $uid = Yii::$app->session->get('uid');//听力1 阅读2 全套5
//        if ($uid == false) {
//            header('Location:https://www.thinkuprep.com/login.html?source=10&url=http://www.thinkuprep.com/cn/mock/list');
//            exit;
//        }
        $data = MockCate::find()->asArray()->select('*,id as cate_id')->orderBy('id asc')->all();
        MockPublic::MockStatus();//将中断超过半小时的模考修改成中断
        $data = ExerciseList::MockRate($data, $type);
        $isInfo = $uid == false ? 0 : MockInfo::find()->asArray()->where('uid=' . $uid)->one() == false ? 0 : 1;
        $user = $uid == false ? '' : User::find()->asArray()->select('userName,image')->where('uid=' . $uid)->one();
        return $this->render('list', ['data' => $data, 'isInfo' => $isInfo,'user'=>$user]);
    }

    /**
     * @Title  阅读引导页
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionGuide()
    {
        $type = Yii::$app->request->get('type', 5);//听力1 阅读2 全套5
        $cate_id = Yii::$app->request->get('cate', 1);//听力1 阅读2 全套5
        $uid = Yii::$app->session->get('uid');//听力1 阅读2 全套5
        if ($uid == false) {
            header("Location:https://www.thinkuprep.com/login.html?source=10&url=http://www.thinkuprep.com//mock/guide.html?type=$type&cate=$cate_id");
            exit;
        }
        if ($type == 1) {
            return $this->render('listenGuide', ['type' => $type, 'cate_id' => $cate_id]);
        } elseif ($type == 2) {
            return $this->render('readGuide', ['type' => $type, 'cate_id' => $cate_id]);
        } else {
            return $this->render('allGuide', ['type' => $type, 'cate_id' => $cate_id]);
        }
    }

    /**
     * @Title  阅读
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionRead()
    {
        $cate_id = Yii::$app->request->get('cate', 1);
        $type = Yii::$app->request->get('type', 2);//听力 2阅读 5全部
        $continue = Yii::$app->request->get('continue');//开始做题重新做题0 1,2继续做题
        return $this->render('read', ['cate' => $cate_id, 'type' => $type, 'continue' => $continue]);
    }

    /**
     * @Title  阅读做题的题目
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionReadData()
    {
        $model = new ExerciseList();
        $cate_id = Yii::$app->request->get('cate', 1);
        $type = Yii::$app->request->get('type', 2);//听力 2阅读 5全部
        $continue = Yii::$app->request->get('continue');//开始做题重新做题0 1,2继续做题
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $pidsStr = MockCate::find()->asArray()->where('id=' . $cate_id)->one()['read'];
        if ($pidsStr == false) {
            die(json_encode(['message' => '暂无题目!', 'code' => 0]));
        }
        $resultid = MockPublic::getResultid($continue, $type, $cate_id);
        $pidsArray = explode(',', $pidsStr);
        foreach ($pidsArray as $key => $val) {
            $name = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where("content_id=$val")->orderBy('content_id asc')->one();
            $pids = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where('cate_id=' . $name['cate_id'] . ' and name="' . $name['name'] . '"')->orderBy('content_id asc')->all();
            $data['data'][$key]['article'] = ExerciseList::find()->where(['pid' => 0, 'content_id' => $pids[0]])->asArray()->one();
            $data['data'][$key]['article']['description'] = ExerciseList::articleformat($data['data'][$key]['article']['description']);
            static $question_list = array();
            foreach ($pids as $k => $v) {
                if ($v != false) {
                    // 阅读多选题判断答案个数
                    $parent = ExerciseList::find()->where(['content_id' => $v])->asArray()->one();
                    $son = ExerciseListDetail::find()->where(['pid' => $v])->asArray()->all();
                    if ($parent['numbering'] == 1) {
                        if ($parent['questionType'] == 2) {
                            $parent['answerCount'] = count($son);
                        } else {
                            $parent['answerCount'] = strlen($son[0]['answer']);
                        }
                    }
                    $data['data'][$key]['topic'][$k]['parent'] = $parent;
                    $data['data'][$key]['topic'][$k]['son'] = $son;
                    foreach ($data['data'][$key]['topic'][$k]['son'] as $ke => $va) {
                        $tmp = MockAnswer::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $resultid)->orderBy('id desc')->one();  //typeid 听阅写口
                        $sign = MockQuestionSign::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $resultid)->one();
                        $answer_list = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp != false ? $tmp['answer'] : '', 'isDo' => $tmp == false ? 0 : 1, 'status' => $sign == false ? 0 : 1];
                        if (($parent['numbering'] == 3 || $parent['numbering'] == 1) && $parent['questionType'] == 1) {
                            $n = $parent['answerCount'] = !empty($son[0]['answer']) ? strlen($son[0]['answer']) : count($son);
                            end($question_list[$key]);
                            $arrayKey = key($question_list[$key]);
                            if($question_list[$key]==false)$question_list[$key]=array();
                            $question_list[$key] += array_fill($arrayKey + 1, $n, $answer_list);
                            $question_list[$key] = array_values($question_list[$key]);
                        } else {
                            $question_list[$key][] = $answer_list;
                        }
                        $data['data'][$key]['topic'][$k]['son'][$ke]['my_answer'] = $tmp != false ? $tmp['answer'] : '';
                        $data['data'][$key]['topic'][$k]['son'][$ke]['judge'] = $tmp != false ? $tmp['result'] : '';
                    }
                }
            }
            $data['data'][$key]['topic'] = $model->readformat($data['data'][$key]['topic']);
            $collect = QuestionCollect::find()->asArray()->where('qid in (' . implode(',', array_column($pids, 'content_id')) . ') and uid=' . $uid)->all();
            $data['data'][$key]['isCollect'] = $collect == false ? 0 : 1;
            $data['data'][$key]['collectId'] = $collect[0]['id'];
        }
        static $n=1;
        foreach($question_list as $k=>$v){
            foreach($v as $key=>$val){
                $question_list[$k][$key]['th']=$n;
                $n+=1;
            }
        }
        //收藏 笔记的数据题目是否收藏
//        $data['isCollect'] = QuestionCollect::isCollect($pidsStr, 2);//pid是否在做题的数组里
        $data['resultid'] = $resultid;
        $data['question_list'] = $question_list;
        $data['code'] = 1;
        $data['user'] = User::find()->asArray()->select('userName,image')->where('uid=' . $uid)->one();
        $data['type'] = $type;
        die(json_encode(['code' => 1, 'message' => '成功！', 'data' => $data]));
    }

    /**
     * @Title  听力
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionListen()
    {
        $cate_id = Yii::$app->request->get('cate', 1);
        $type = Yii::$app->request->get('type', 2);//听力 2阅读 5全部
        $continue = Yii::$app->request->get('continue');//开始做题重新做题0 1,2继续做题
        return $this->render('listen', ['cate' => $cate_id, 'type' => $type, 'continue' => $continue]);
    }

    /**
     * @Title  听力做题的题目
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionListenData()
    {
        $model = new ExerciseList();
        $type = Yii::$app->request->get('type', 1);//听力1 全部 5
        $continue = Yii::$app->request->get('continue');//0开始 1继续
        $cate_id = Yii::$app->request->get('cate', 2);
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $resultid = MockPublic::getResultid($continue, $type, $cate_id);
        $pidsStr = MockCate::find()->asArray()->where('id=' . $cate_id)->one()['listen'];
        if ($pidsStr == false) {
            die(json_encode(['message' => '暂无题目!', 'code' => 0]));
        }
        $pidsArray = explode(',', $pidsStr);
        foreach ($pidsArray as $key => $val) {
            $name = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where("content_id=$val")->orderBy('content_id asc')->one();
            $pids = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where('cate_id=' . $name['cate_id'] . ' and name="' . $name['name'] . '"')->orderBy('content_id asc')->all();
            if ($pids == false) {
                die(json_encode(['message' => '暂无题目!', 'code' => 0]));
            }
            $pids = array_column($pids, 'content_id');
            $data['data'][$key]['article'] = ExerciseList::find()->where(['pid' => 0, 'content_id' => $pids[0]])->asArray()->one();
            static $question_list = array();
            foreach ($pids as $k => $v) {
                if ($v != false) {
                    $parent = ExerciseList::find()->where(['content_id' => $v])->asArray()->one();
                    $son = ExerciseListDetail::find()->where(['pid' => $v])->asArray()->all();
                    if ($parent['type'] == 3) {
                        if ($parent['questionType'] == 2) {
                            $parent['answerCount'] = count($son);
                        } else {
                            $parent['answerCount'] = !empty($son[0]['alternatives']) ? strlen($son[0]['alternatives']) : strlen($son[0]['answer']);
                        }
                    }
                    $data['data'][$key]['topic'][$k]['parent'] = $parent;
                    $data['data'][$key]['topic'][$k]['son'] = $son;
                    foreach ($data['data'][$key]['topic'][$k]['son'] as $ke => $va) {
                        $tmp = MockAnswer::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $resultid)->orderBy('id desc')->one();  //typeid 听阅写口
                        $sign = MockQuestionSign::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $resultid)->one();
                        $answer_list = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp != false ? $tmp['answer'] : '', 'isDo' => $tmp == false ? 0 : 1, 'status' => $sign == false ? 0 : 1];
                        if (($parent['type'] == 3 || $parent['type'] == 4) && $parent['questionType'] == 1) {
                            $n = $parent['answerCount'] = !empty($son[0]['alternatives']) ? strlen($son[0]['alternatives']) : strlen($son[0]['answer']);
                            end($question_list[$key]);
                            $arrayKey = key($question_list[$key]);
                            $question_list[$key] = $question_list[$key] == false ? array() : $question_list[$key];
                            $question_list[$key] += array_fill($arrayKey + 1, $n, $answer_list);
                            $question_list[$key] =array_values($question_list[$key]);
                        } else {
                            $question_list[$key][] =$answer_list;
                        }
                        $data['data'][$key]['topic'][$k]['son'][$ke]['my_answer'] = $tmp == false ? '' : $tmp['answer'];
                        $data['data'][$key]['topic'][$k]['son'][$ke]['judge'] = $tmp == false ? '' : $tmp['result'];
                    }
                    // 2021-11-30 添加浏览量计数
                    ExerciseList::updateAll(['viewCount' => $parent['viewCount'] + 1], 'id=' . $parent['id']);
                }
            }
            $data['data'][$key]['topic'] = $model->listenMockFormat($data['data'][$key]['topic'],$resultid);
            $data['data'][$key]['listeningFile'] = $data['data'][$key]['topic'][0]['parent']['listeningFile'];
            $collect = QuestionCollect::find()->asArray()->where('qid in (' . implode(',', $pids). ') and uid=' . $uid)->all();
            $data['data'][$key]['isCollect'] = $collect == false ? 0 : 1;
            $data['data'][$key]['collectId'] = $collect[0]['id'];
        }
        $data['Remarks'] = QuestionRemarks::getRemarks($pidsStr);//pid是否在做题的数组里
        $data['user'] = User::find()->asArray()->select('userName,image')->where('uid=' . $uid)->one();
        $data['resultid'] = $resultid;
        $data['question_list'] = $question_list;
        $data['code'] = 1;
        $data['type'] = $type;
        die(json_encode(['code' => 1, 'message' => '成功！', 'data' => $data]));
    }

    /**
     * @Title  写作
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionWrite()
    {
        $cate_id = Yii::$app->request->get('cate', 1);
        $type = Yii::$app->request->get('type', 2);//听力 2阅读 5全部
        $continue = Yii::$app->request->get('continue');//开始做题重新做题0 1,2继续做题
        return $this->render('write', ['cate' => $cate_id, 'type' => $type, 'continue' => $continue]);
    }

    /**
     * @Title  写作做题
     * @Author yoyo
     * @Date   2023-05-06
     */
    public function actionWriteData()
    {
        $type = Yii::$app->request->get('type', 5);//听力1 全部 5
        $continue = Yii::$app->request->get('continue');//0开始 1继续
        $cate_id = Yii::$app->request->get('cate', 1);
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $pidsStr = MockCate::find()->asArray()->where('id=' . $cate_id)->one()['write'];
        // 查询父类
        $parent = ExerciseList::find()->where('content_id in (' . $pidsStr . ')')->asArray()->all();
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $resultid = MockPublic::getResultid($continue, $type, $cate_id);
        foreach ($parent as $k => $v) {
            $parent[$k]['son'] = ExerciseListDetail::find()->where('pid =' . $v['content_id'])->asArray()->one();
            $tem = MockAnswer::find()->asArray()->where('content_id=' . $parent[$k]['son']['content_id'] . " and uid=$uid and pub_id=$resultid")->orderBy('id desc')->one();
            $parent[$k]['son']['userAnswer'] = $tem != false ? $tem['answer'] : '';
            $parent[$k]['son']['my_answer'] = $tem != false ? $tem['answer'] : 0;
            $collect = QuestionCollect::find()->asArray()->where('qid ='.$v['content_id'].' and uid=' . $uid)->all();
            $parent[$k]['isCollect'] = $collect == false ? 0 : 1;
            $parent[$k]['collectId'] = $collect[0]['id'];
        }
        $user = User::find()->asArray()->select('userName,image')->where('uid=' . $uid)->one();
        die(json_encode(['code' => 1, 'message' => '成功！', 'data' => ['data' => $parent, 'resultid' => $resultid, 'user' => $user]]));

    }

    /**
     * @Title  保存答案
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionSaveAnswer()
    {
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $pub_id = Yii::$app->request->post('resultid');
        $type = Yii::$app->request->post('typeid');//听力1 阅读2 写作3
        $content = json_decode(Yii::$app->request->post('content'), true);//答案的json
        $pubData = MockPublic::find()->asArray()->where('id=' . $pub_id)->one();
        // 查父级content_id
        if ($type != 3) {
            foreach ($content as $key => $val) {
                foreach ($val as $ke => $va) {
                    foreach ($va as $k => $v) {
                        $insert['content_id'] = $v['content_id'];//小题的id
                        $insert['pub_id'] = $pub_id;//同一次做题的id
                        $insert['answer'] = $answer = $v['answer'];//用户答案
                        $insert['really'] = $really = $v['trueAnswer'];//正确答案
                        $insert['uid'] = $uid;
                        $insert['typeid'] = $type;
                        $insert['time'] = $v['createTime'] < 943891200 ? $v['createTime'] : 0;
                        $insert['createtime'] = ($v['createTime'] == false || $v['createTime'] < 943891200) ? time() : $v['createTime'];
                        $answer = strtolower(ExerciseResult::romanNumber(trim($answer)));
                        $really = strtolower(ExerciseResult::romanNumber(trim($really)));
                        $insert['result'] = MockAnswer::checkAnswer($answer, $really);
                        $sign = MockAnswer::find()->asArray()->where("content_id=" . $v['content_id'] . " and uid=$uid and pub_id=$pub_id ")->one();
                        if ($sign) {
                            $re = MockAnswer::updateAll(['answer' => $insert['answer'], 'result' => $insert['result']], "uid=$uid and pub_id=$pub_id and content_id=" . $v['content_id']);
                        } else {
                            $re = Yii::$app->db->createCommand()->insert("{{%mock_answer}}", $insert)->execute();
                        }
                    }
                }
            }
        } else {
            foreach ($content as $k => $v) {
                $insert['content_id'] = $v['content_id'];//小题的id
                $insert['pub_id'] = $pub_id;//同一次做题的id
                $insert['answer'] = $answer = $v['answer'];//用户答案
                $insert['really'] = $really = $v['trueAnswer'];//正确答案
                $insert['uid'] = $uid;
                $insert['typeid'] = $type;
                $insert['time'] = $v['createTime'];
                $insert['createtime'] = time();
                $insert['result'] = 1;
                $sign = MockAnswer::find()->asArray()->where("content_id=" . $v['content_id'] . " and uid=$uid and pub_id=$pub_id ")->one();
                if ($sign) {
                    $re = MockAnswer::updateAll(['answer' => $insert['answer'], 'result' => $insert['result']], "uid=$uid and pub_id=$pub_id and content_id=" . $v['content_id']);
                } else {
                    $re = Yii::$app->db->createCommand()->insert("{{%mock_answer}}", $insert)->execute();
                }
            }
        }
        if ($pubData['type'] != 5) {
            MockPublic::updateAll(['status' => 1, 'endTime' => time()], 'id=' . $pub_id);
        } else {
            if ($type == 3) MockPublic::updateAll(['status' => 1, 'endTime' => time()], 'id=' . $pub_id);
        }
        die(json_encode(['message' => '保存成功', 'code' => 1]));
    }

    /**
     * @Title  提交
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionSubmit()
    {
        $pub_id = Yii::$app->request->post('resultid');
        MockPublic::updateAll(['status' => 1, 'endTime' => time()], 'id=' . $pub_id);
        die(json_encode(['message' => '保存成功', 'code' => 1]));
    }

    /**
     * @Title  结果
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionResult()
    {
        $cate_id = Yii::$app->request->get('cate');
        $type = Yii::$app->request->get('type');
        $uid = Yii::$app->session->get('uid');//使用uid
        if (!$uid) {
            die(json_encode(['code' => 5, 'message' => '未登录！']));
        }
        $pubData = MockPublic::find()->asArray()->where('mockcate_id=' . $cate_id . ' and uid=' . $uid . ' and type=' . $type)->orderBy('id desc')->one();
        if (!$pubData) {
            die(json_encode(['code' => 0, 'message' => '无做题记录！']));
        }
        $time = date('Y.m.d H:i', $pubData['endTime']);
        //记录
        if ($type == 1) {
            $cate = MockCate::find()->asArray()->select('listen')->where('id=' . $cate_id)->one();
        } elseif ($type == 2) {
            $cate = MockCate::find()->asArray()->select('read')->where('id=' . $cate_id)->one();
        } else {
            $cate = MockCate::find()->asArray()->select('listen,read,write')->where('id=' . $cate_id)->one();
        }
        $data = MockAnswer::getMockDetail($cate, $pubData);
        $data['allTime'] = floor(($pubData['endTime'] - $pubData['startTime']) / 60) . 'm' . (($pubData['endTime'] - $pubData['startTime']) % 60) . 's';
        $data['name'] = '雅思机考模拟' . Yii::$app->params['noToStr'][$cate_id];
        $data['time'] = $time;
        $data['user'] = User::find()->asArray()->select('userName,image')->where('uid=' . $uid)->one();
        $data['resultid'] = $pubData['id'];
        return $this->render('result', ['data' => $data]);
    }

    /**
     * @title 模考用户收集
     * @Author yoyo
     * @Date   2023-4-27
     */
    public function actionGetInfo()
    {
        $uid = Yii::$app->session->get('uid');
        $phone = Yii::$app->request->post('phone', '');
        $wx = strip_tags(Yii::$app->request->post('wx', ''));
        $score = Yii::$app->request->post('score', '');
        $re = Yii::$app->db->createCommand()->insert('x2_mock_info', ['wx' => $wx, 'phone' => $phone, 'score' => $score, 'createTime' => time(), 'uid' => $uid])->execute();
        if ($re) {
            die(json_encode(['code' => 1, 'message' => '修改成功！']));
        }
    }

    /**
     * @Title  报错
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionReport()
    {
        $reData['contentId'] = Yii::$app->request->post('contentId');//pid
        $reData['reportType'] = Yii::$app->request->post('reportType');
        $reData['description'] = htmlspecialchars(Yii::$app->request->post('description'));
        $reData['type'] = Yii::$app->request->post('type');
        $reData['createTime'] = time();
        $session = Yii::$app->session;
        $reData['uid'] = $session->get('uid');//使用uid
        if (!$reData['uid']) {
            die(json_encode(['code' => 5, 'message' => '未登录！']));
        }
        $re = Yii::$app->db->createCommand()->insert("{{%mock_question_report}}", $reData)->execute();
        if ($re) {
            die(json_encode(['code' => 1, 'message' => '提交成功！']));
        } else {
            die(json_encode(['code' => 0, 'message' => '提交失败！']));
        }
    }

    /**
     * @Title  添加笔记
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionAddRemarks()
    {
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $remarks = strip_tags(Yii::$app->request->post('remark'));
        $sign = Yii::$app->request->post('sign');
        $content_id = Yii::$app->request->post('content_id');
        $id = Yii::$app->request->post('id');
        $model = new QuestionRemarks();
        $model->content_id = $content_id;
        $model->sign = $sign;
        $model->uid = $uid;
        $model->remarks = $remarks;
        $model->createTime = time();
        if ($id == false) {
            $re = $model->save();
        } else {
            $re = QuestionRemarks::updateAll(['remarks' => $remarks], 'id=' . $id);
        }
        if ($re != false) {
            die(json_encode(['code' => 1, 'message' => '成功']));
        } else {
            die(json_encode(['code' => 0, 'message' => '失败']));
        }
    }

    /**
     * @Title  添加题目收藏
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionCollection()
    {
        $uid = Yii::$app->session->get('uid');
        $id = Yii::$app->request->post('content_id');
        $typeid = Yii::$app->request->post('typeid');
        $catId = Yii::$app->request->post('catId');
        if (!$uid) {
            die(json_encode(['code' => 5, 'message' => '未登录！']));
        }
        $status = QuestionCollect::IsCollect($id, $typeid);
        if ($status) {
            die(json_encode(['code' => 0, 'message' => '已收藏，不能重复收藏！']));
        }
        $re = Yii::$app->db->createCommand()->insert("{{%user_question_collect}}", ['qid' => $id, 'uid' => $uid, 'typeid' => $typeid, 'catId' => $catId, 'createTime' => time()])->execute();
        if ($re) {
            $tem = Yii::$app->db->createCommand("SELECT id from {{%user_question_collect}} where qid=$id and uid=$uid")->queryOne();
            die(json_encode(['code' => 1, 'message' => '收藏成功', 'data' => ['id' => $tem['id']]]));
        } else {
            die(json_encode(['code' => 0, 'message' => '收藏失败']));
        }

    }

    /**
     * @Title  删除题目收藏
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionDeleteCollection()
    {
        $uid = Yii::$app->session->get('uid');
        $id = Yii::$app->request->post('id');
        if (!$uid) {
            die(json_encode(['code' => 5, 'message' => '未登录！']));
        }
        $re = QuestionCollect::deleteAll('id = :id ', array(':id' => $id));
        if ($re) {
            die(json_encode(['code' => 1, 'message' => '取消成功']));
        } else {
            die(json_encode(['code' => 0, 'message' => '取消失败!']));
        }

    }

    /**
     * @Title  详情页
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionDetail()
    {
        $resultid = Yii::$app->request->get('resultid');
        $subject = Yii::$app->request->get('subject', 'listen');//listen read write
        $public = MockPublic::find()->asArray()->where('id=' . $resultid)->one();
        if ($subject == 'listen') {
            return $this->render('listenDetail', ['public' => $public]);
        } elseif ($subject == 'read') {
            return $this->render('readDetail', ['public' => $public]);
        } else {
            return $this->render('writeDetail', ['public' => $public]);
        }
    }

    /**
     * @Title  做题的详情
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionDetailData()
    {
        $model = new ExerciseList();
        $resultid = Yii::$app->request->get('resultid');
        $subject = Yii::$app->request->get('subject', 'listen');//listen read write
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 5]));
        }
        $public = MockPublic::find()->asArray()->where('id=' . $resultid)->one();
        if ($public == false) {
            die(json_encode(['message' => '暂无结果!', 'code' => 0]));
        }
        $cate = MockCate::find()->asArray()->where('id=' . $public['mockcate_id'])->one();
        $pidsArray = explode(',', $cate[$subject]);
        foreach ($pidsArray as $key => $val) {
            $name = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where("content_id=$val")->orderBy('content_id asc')->one();
            $pids = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where('cate_id=' . $name['cate_id'] . ' and name="' . $name['name'] . '"')->orderBy('content_id asc')->all();
            $data['data'][$key]['article'] = ExerciseList::find()->where(['pid' => 0, 'content_id' => $pids[0]])->asArray()->one();
            $data['data'][$key]['article']['description'] = ExerciseList::articleformat($data['data'][$key]['article']['description']);
            static $question_list = array();
            foreach ($pids as $k => $v) {
                if ($v != false) {
                    // 阅读多选题判断答案个数
                    $parent = ExerciseList::find()->where(['content_id' => $v])->asArray()->one();
                    $son = ExerciseListDetail::find()->where(['pid' => $v])->asArray()->all();
                    if ($parent['numbering'] == 1) {
                        if ($parent['questionType'] == 2) {
                            $parent['answerCount'] = count($son);
                        } else {
                            $parent['answerCount'] = strlen($son[0]['answer']);
                        }
                    }
                    $data['data'][$key]['topic'][$k]['parent'] = $parent;
                    $data['data'][$key]['topic'][$k]['son'] = $son;
                    foreach ($data['data'][$key]['topic'][$k]['son'] as $ke => $va) {
                        $tmp = MockAnswer::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $resultid)->orderBy('id desc')->one();  //typeid 听阅写口
//                        $question_list[$key][] = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp == false ? '' : $tmp['answer'], 'isDo' => $tmp == false ? 0 : 1];

                        if ($subject == 'listen') {
                            $answer_list = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp != false ? $tmp['answer'] : '', 'isDo' => $tmp == false ? 0 : 1];
                            if (($parent['type'] == 3 || $parent['type'] == 4) && $parent['questionType'] == 1) {
                                $n = $parent['answerCount'] = !empty($son[0]['alternatives']) ? strlen($son[0]['alternatives']) : strlen($son[0]['answer']);
                                end($question_list[$key]);
                                $arrayKey = key($question_list[$key]);
                                $question_list[$key] = $question_list[$key] == false ? array() : $question_list[$key];
                                $question_list[$key] += array_fill($arrayKey + 1, $n, $answer_list);
                                $question_list[$key] = array_values($question_list[$key]);
                            } else {
                                $question_list[$key][] = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp != false ? $tmp['answer'] : '', 'isDo' => $tmp == false ? 0 : 1];
                            }
                        } else {
                            $tmp = MockAnswer::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $resultid)->orderBy('id desc')->one();  //typeid 听阅写口
                            $answer_list = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp != false ? $tmp['answer'] : '', 'isDo' => $tmp == false ? 0 : 1];
                            if (($parent['numbering'] == 3 || $parent['numbering'] == 1)&& $parent['questionType'] == 1) {
                                $n = $parent['answerCount'] = !empty($son[0]['answer']) ? strlen($son[0]['answer']) : count($son);
                                end($question_list[$key]);
                                $arrayKey = key($question_list[$key]);
                                $question_list[$key] = $question_list[$key] == false ? array() : $question_list[$key];
                                $question_list[$key] += array_fill($arrayKey + 1, $n, $answer_list);
                                $question_list[$key] =array_values($question_list[$key]);
                            } else {
                                $question_list[$key][] = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp != false ? $tmp['answer'] : '', 'isDo' => $tmp == false ? 0 : 1];
                            }
                        }
                        $data['data'][$key]['topic'][$k]['son'][$ke]['my_answer'] = $tmp != false ? $tmp['answer'] : '';
                        $data['data'][$key]['topic'][$k]['son'][$ke]['judge'] = $tmp != false ? $tmp['result'] : '';
                    }
                }
            }
            if($subject=='listen'){
                $data['data'][$key]['topic'] = $model->listenMockFormat($data['data'][$key]['topic'],$resultid);
                $data['data'][$key]['listeningFile'] = $data['data'][$key]['topic'][0]['parent']['listeningFile'];

            }elseif($subject=='read'){
                $data['data'][$key]['topic'] = $model->readformat($data['data'][$key]['topic']);
            }
            $collect = QuestionCollect::find()->asArray()->where('qid in (' . implode(',', array_column($pids, 'content_id')) . ') and uid=' . $uid)->all();
            $data['data'][$key]['isCollect'] = $collect == false ? 0 : 1;
            $data['data'][$key]['collectId'] = $collect[0]['id'];
        }
        //收藏 笔记的数据题目是否收藏
//        var_dump($pidsStr);die;
//        $data['isCollect'] = QuestionCollect::isCollect($cate[$subject], 2);//pid是否在做题的数组里
        $data['resultid'] = $resultid;
        foreach($question_list as $k=>$v){
            foreach($v as $key=>$val){
                $question_list[$k][$key]['th']=$n;
                $n+=1;
            }
        }
        $data['question_list'] = $question_list;
        $data['code'] = 1;
        if ($public['type'] == 1) {
            $data['type'] = ['listen'];
        } elseif ($public['type'] == 2) {
            $data['type'] = ['read'];
        } else {
            $data['type'] = ['listen', 'read', 'write'];
        }
        die(json_encode(['code' => 1, 'message' => '成功！', 'data' => $data]));
    }

    /**
     * @Title  题目标记
     * @Author yoyo
     * @Date   2023-05-06
     */
    public function actionAddReview()
    {
        $uid = Yii::$app->session->get('uid');
        $pub_id = Yii::$app->request->get('pub_id');
        $content_id = Yii::$app->request->get('content_id');
        $tmp = MockQuestionSign::find()->where(['uid'=>$uid, 'pub_id'=>$pub_id, 'content_id'=>$content_id])->asArray()->one();
        if (empty($tmp)) {
            $model = new MockQuestionSign();
            $model->pub_id = $pub_id;
            $model->content_id = $content_id;
            $model->uid = $uid;
            if ($model->save()) {
                $res['code'] = 1;
                $res['message'] = 'success';
            } else {
                $res['code'] = 0;
                $res['message'] = 'fail';
            }
        } else {
            $res['code'] = 1;
            $res['message'] = 'success';
        }
        die(json_encode($res));
    }
}
